package server

import (
	"data_service/models"
	"time"

	"data_service/server/websocket"
)

// 房间服务接口
type RoomService interface {
	CreateRoom(name, creatorID, creatorName string, maxUsers int) (string, error)
	GetRoom(id string) *websocket.Room
	GetAllRooms() []*websocket.Room
	DeleteRoom(id string) error
	GetRoomUsers(id string) []map[string]interface{}
	SetRoomEmptySince(id string, t time.Time) error
	ClearRoomEmptySince(id string) error
}

// 房间服务实现
type roomService struct {
	wsServer *websocket.WebSocketServer
}

// 创建新的房间服务
func NewRoomService(wsServer *websocket.WebSocketServer) RoomService {
	return &roomService{
		wsServer: wsServer,
	}
}

// 创建房间
func (s *roomService) CreateRoom(name, creatorID, creatorName string, maxUsers int) (string, error) {
	roomID := s.wsServer.CreateRoom(name, creatorID, creatorName, maxUsers)
	return roomID, nil
}

// 获取房间
func (s *roomService) GetRoom(id string) *websocket.Room {
	return s.wsServer.GetRoom(id)
}

// 获取所有房间
func (s *roomService) GetAllRooms() []*websocket.Room {
	s.wsServer.Mu.RLock()
	defer s.wsServer.Mu.RUnlock()

	var rooms []*websocket.Room
	for _, room := range s.wsServer.Rooms {
		rooms = append(rooms, room)
	}
	return rooms
}

// 删除房间
func (s *roomService) DeleteRoom(id string) error {
	s.wsServer.Mu.Lock()
	defer s.wsServer.Mu.Unlock()

	if room, exists := s.wsServer.Rooms[id]; exists {
		// 通知房间内所有用户
		leaveMsg := websocket.Message{
			Type:    99,
			Content: "房间已被删除",
			Time:    time.Now().Unix(),
		}
		room.Broadcast(leaveMsg)

		// 关闭所有客户端连接
		room.Mu.RLock()
		for _, client := range room.Clients {
			client.Mu.Lock()
			close(client.Send)
			if client.Conn != nil {
				client.Conn.Close()
			}
			client.Mu.Unlock()
		}
		room.Mu.RUnlock()

		// 从内存中删除房间
		delete(s.wsServer.Rooms, id)

		// 从数据库中删除房间
		return models.DeleteRoomByID(id)
	}
	return nil
}

// 获取房间用户列表
func (s *roomService) GetRoomUsers(id string) []map[string]interface{} {
	room := s.wsServer.GetRoom(id)
	if room == nil {
		return nil
	}
	return room.GetUserList()
}

// 设置房间为空时间
func (s *roomService) SetRoomEmptySince(id string, t time.Time) error {
	return models.SetRoomEmptySince(id, t)
}

// 清空房间为空时间
func (s *roomService) ClearRoomEmptySince(id string) error {
	return models.ClearRoomEmptySince(id)
}
